# -*- coding: utf-8 -*-
# @Time    : 2024/1/11 20:06
# @Author  : micah
# @File    : 13.bs4的简单使用.py
# @Software: PyCharm

import re
from bs4 import BeautifulSoup


html_str = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""

# 1.创建soup对象
soup = BeautifulSoup(html_str, 'lxml')

# 2.将文档格式化输出
# print(soup.prettify())  # 格式化输出的


"""find_all方法: 查询在文档中符合条件的所有标签, 返回结果的类型是一个列表"""
res_1 = soup.find_all('b')  # 返回了一个列表
res_2 = soup.find_all('a')  # 返回了一个列表
print(res_1, res_2)

# 查询以b开头的所有标签内容
res_3 = soup.find_all(re.compile('^b'))
# print(res_3)

# 可以将一个列表作为一个参数进行传递
res_4 = soup.find_all(['a', 'b'])
# print(res_4)  # 返回了一个列表

res_5 = soup.find_all('li')
# print(res_5)  # 如果提取的标签不存在则返回一个空列表


"""attrs参数: 按照标签属性与属性值完成数据提取"""
res_6 = soup.find_all(attrs={'class': 'sister'})
print(res_6)

print('-' * 30)

res_7 = soup.find_all(class_='sister')  # class是python中的关键字, 必须使用下划线做区分
print(res_7)

print('-' * 30)

"""string参数: 按照标签包含的文本信息进行匹配提取"""
res_8 = soup.find_all(string='Lacie')
print(res_8)
print('-' * 30)
res_9 = soup.find_all(string=['Elsie', 'Lacie', 'Tillie'])
print(res_9)

print('-' * 30)

"""find方法: 查询在文档中符合条件的第一个标签"""
res_10 = soup.find('a')
print(res_10)












